<script setup>
import DialogPro from "@/components/DialogPro.vue";
import { addShortcut } from "@/api/user.js";
import { reactive, ref,nextTick,onMounted } from "vue";
import { useRouter } from "vue-router";
const router = useRouter();
import { useHomeStore } from "@/stores/home";
const useStore = useHomeStore();
const urlRef = ref();

const data = reactive({
  url: "",
  title: "",
  mediaQuery: window.matchMedia("(max-width: 768px)")
})

function validateUrl(url) {
  const reg = /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/;
  return reg.test(url);
}
// onMounted(()=>{
//   nextTick(()=>{
//     urlRef.$refs.focus()
//   })
// })
const handleSubmit = () => {
  if (validateUrl(data.url)) {
    addShortcut(data.title !== '' ? data.title : null, data.url, null).then((res) => {
      console.log(res);
      if (res.code === 20000) {
        ElMessage({
          showClose: true,
          message: "添加成功",
          type: "success",
        });
        useStore.addShortcut(res.retData)
        useStore.showAddUrlWindow = false
      } else {
        ElNotification({
            title: "",
            type: "warning",
            message: res.message,
          });
      }
    });
  } else {
    ElMessage({
      showClose: true,
      message: "输入的网址不正确",
      type: "error",
    });
  }
};
</script>

<template>
  <DialogPro v-model="useStore.showAddUrlWindow" title="添加网址">
    <div class="form-wrapper">
      <el-form label-position="left">
        <el-form-item label="网址">
          <el-input
              ref="urlRef"
              :clearable="true"
              autofocus
              v-model="data.url"
              placeholder="请输入添加网址"
              autocomplete="off"
              @keydown.enter="handleSubmit"
          />
        </el-form-item>
        <el-form-item label="名称">
          <el-input
              v-model="data.title"
              placeholder="留空则自动获取"
              autocomplete="off"
              @keydown.enter="handleSubmit"
          />
        </el-form-item>
      </el-form>
      <el-button style="width:min(90%,150px);margin:auto;" type="primary" color="black" @click="handleSubmit">
        添加
      </el-button>
    </div>
  </DialogPro>
</template>

<style lang="less" scoped>
.form-wrapper {
  display: flex;
  flex-flow: column;
}
</style>